<template>
    <view class="pages" :class="GlobalThemes.commonBackGroundClass">
        <view class="search-top-box" id="navbar">
            <u-navbar
                back-icon-color="#ffffff"
                :is-back="true"
                :border-bottom="false"
                :background="typelist[tabIndex].background"
            >
                <view class="mp-name">
                    <text>{{ i18n('index').appName }}</text>
                </view>
            </u-navbar>
        </view>
        <view class="cu-bar bg-my-light-black">
            <view class="action">
                <text class="cuIcon-title text-my-red"></text>
                {{ i18n('user').feekbackTitle }}
            </view>
        </view>
        <view class="cu-form-group margin-top">
            <view class="title">{{ i18n('user').feekbackType }}</view>
            <picker @change="PickerChange" :value="select" :range="type">
                <view class="picker">{{ type[select] }}</view>
            </picker>
        </view>
        <view class="cu-form-group align-start solid-bottom">
            <view class="title">{{ i18n('user').feekbackContent }}</view>
            <textarea
                maxlength="200"
                @focus="hideKeybord"
                v-model="formData.content"
                :placeholder="i18n('user').feekbackContentPlaceholder"
            ></textarea>
        </view>
        <view class="cu-bar bg-my-light-black">
            <view class="action">{{ i18n('user').imgUploadText }}</view>
            <view class="action">{{ imgList.length }}/4</view>
        </view>
        <view class="cu-form-group margin-top">
            <view class="grid col-4 grid-square flex-sub">
                <view class="bg-img" v-for="(item, index) in imgList" :key="index" @tap="ViewImage" :data-url="imgList[index]">
                    <image :src="imgList[index]" mode="aspectFill"></image>
                    <view class="cu-tag bg-red" @tap.stop="DelImg" :data-index="index"><text class="cuIcon-close"></text></view>
                </view>
                <view class="solids" @tap="ChooseImage" v-if="imgList.length < 4"><text class="cuIcon-cameraadd"></text></view>
            </view>
        </view>
        <view class="cu-form-group margin-top solid-bottom" v-if="!isLogin">
            <view class="title">{{ i18n('user').connecText }}</view>
            <input :placeholder="i18n('user').connecPlaceholderText" type="number" v-model="formData.contact" />
        </view>
        <view class="padding flex flex-direction">
            <u-button :loading="saveLoading" type="success" :disabled="saveLoading" @click="save">
                {{ i18n('user').saveBtn }}
            </u-button>
        </view>

        <!-- #ifdef MP-WEIXIN -->
        <!-- 广告 -->
        <Adview v-if="adSwitchKg" :adSwitchKg="adSwitchKg" :homeADList="oneAd"></Adview>
        <!-- #endif -->

        <!-- 加载条 -->
        <w-loading :text="i18n('common').submit" mask="true" click="false" ref="loading"></w-loading>
    </view>
</template>

<script>
import Adview from '@/components/home-ad/ad-view.vue';
const MyApp = getApp();
const globalData = MyApp.globalData;
import { pathToBase64, base64ToPath } from 'image-tools';
export default {
    components: {
        Adview
    },
    data() {
        return {
            adSwitchKg: globalData.adSwitchKg || uni.getStorageSync('sys_config').ad_switch,
            oneAd: MyApp.getOneAd('alert_public'),
            tabIndex: 0,
            typelist: globalData.typelist,
            isLogin: false,
            select: 0,
            type: [
                globalData.$t('user').feedbackTypeOne,
                globalData.$t('user').feedbackTypeTwo,
                globalData.$t('user').feedbackTypeThree
            ],
            imgList: [],
            formData: {
                type: globalData.$t('user').feedbackTypeOne,
                content: '',
                imgs: [],
                contact: ''
            },
            imgTmp: null,
            saveLoading: false,
            ishide: false
        };
    },
    computed: {
        i18n() {
            return globalData.$t;
        }
    },
    mounted() {
        this.init();
    },
    methods: {
        hideKeybord(){
            if (!this.ishide) {
                let _this = this;
                setTimeout( v=> {
                    uni.hideKeyboard();
                }, 1500);
                this.ishide = true;
            }  
        },
        init() {
            this.isLogin = MyApp.checkLogin();
        },
        save() {
            let _this = this;
            if (_this.formData.content.length <= 0) {
                uni.showToast({ title: _this.i18n('user').pleaseInputContent, icon: 'none' });
                return false;
            }
            if (!_this.isLogin && _this.formData.contact.length <= 0) {
                uni.showToast({ title: _this.i18n('user').pleaseInputConnectInfo, icon: 'none' });
                return false;
            }
            if (_this.formData.imgs.length > 0) {
                _this.formData.imgs = _this.formData.imgs.join(',');
            }
            _this.formData.encryptedData = 1;
            _this.saveLoading = true;
            _this.$http
                .post('/user/user/feedback', _this.formData)
                .then(res => {
                    _this.saveLoading = false;
                    if (res.code == 200) {
                        _this.formData = {
                            type: _this.i18n('user').feedbackTypeOne,
                            content: '',
                            imgs: [],
                            contact: ''
                        };
                        _this.imgList = [];
                        uni.showToast({
                            title: '反馈成功',
                            icon: 'none'
                        })
                    }
                })
                .catch(err => {
                    _this.saveLoading = false;
                });
        },
        PickerChange(e) {
            this.select = e.detail.value;
            this.formData.type = this.type[e.detail.value];
        },
        ChooseImage() {
            let _this = this;
            uni.chooseImage({
                count: 1,
                sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
                sourceType: ['album'], //从相册选择
                success: res => {
                    if (_this.imgList.length != 0) {
                        _this.imgList = _this.imgList.concat(res.tempFilePaths);
                    } else {
                        _this.imgList = res.tempFilePaths;
                    }
                    _this.imgToBase64(res);
                }
            });
        },
        ViewImage(e) {
            uni.previewImage({
                urls: this.imgList,
                current: e.currentTarget.dataset.url
            });
        },
        DelImg(e) {
            this.imgList.splice(e.currentTarget.dataset.index, 1);
            this.formData.imgs.splice(e.currentTarget.dataset.index, 1);
        },
        imgToBase64(chooseImageRes) {
            let _this = this;
            // #ifdef APP-PLUS
            for (let i = 0; i <= chooseImageRes.tempFilePaths.length; i++) {
                plus.io.resolveLocalFileSystemURL(chooseImageRes.tempFilePaths[i], function(entry) {
                    entry.file(function(file) {
                        var fileReader = new plus.io.FileReader();
                        fileReader.readAsDataURL(file);
                        fileReader.onloadend = function(evt) {
                            // 上传图片 ，返回服务器图片路径
                            _this.checkImgByHttp(evt.target.result);
                        };
                    });
                });
            }
            // #endif

            // #ifdef MP-WEIXIN
            uni.getFileSystemManager().readFile({
                filePath: chooseImageRes.tempFilePaths[0], //选择图片返回的相对路径
                encoding: 'base64', //编码格式
                success: res => {
                    //成功的回调
                    let base64 = 'data:image/jpeg;base64,' + res.data; //不加上这串字符，在页面无法显示的哦
                    _this.checkImgByHttp(base64);
                }
            });
            // #endif

            // #ifdef H5
            pathToBase64(chooseImageRes.tempFilePaths[0]).then(base64 => {
                _this.checkImgByHttp(base64);
            });
            // #endif
        },
        uploadImg(img) {
            let _this = this;
            let formValue = {
                code: img,
                type: 'feedback',
                encryptedData: 1
            };
            _this.$http
                .post('/attachment/attachment/uploadImg', formValue)
                .then(res => {
                    MyApp.closeLoading(_this.$refs.loading);
                    if (res.code == 200) {
                        _this.formData.imgs = _this.formData.imgs.concat(res.data.file);
                    }
                })
                .catch(err => {});
        },
        checkImgByHttp(imgs) {
            let _this = this;
            // https检测 用时较长
            MyApp.showLoading(_this.$refs.loading);
            let sys = uni.getStorageSync('sys_config');
            if (
                sys.show_xx && !sys.member_group_switch ||
                (sys.member_group_switch &&
                sys.userinfo.hasOwnProperty('group_id') &&
                sys.userinfo.group_id < sys.member_group_limit)
                
            ) {
                _this.$http
                    .post('/videos/home/checkImg', {
                        str: imgs,
                        encryptedData: 1
                    })
                    .then(res => {
                        if (200 != res.code) {
                            MyApp.closeLoading(_this.$refs.loading);
                            uni.showModal({
                                title: _this.i18n('common').waringText,
                                content: _this.i18n('common').waringImgText,
                                showCancel: false
                            });
                            return false;
                        } else {
                            _this.uploadImg(imgs);
                        }
                    })
                    .catch(res => {
                        MyApp.closeLoading(_this.$refs.loading);
                        uni.showToast({
                            title: _this.i18n('common').networkError,
                            icon: 'none'
                        });
                    });
            } else {
                _this.uploadImg(imgs);
            }
        }
    }
};
</script>

<style>
.solids::after {
    border: 1rpx solid #45506a;
}
</style>
